package slh.myMapReduce;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import slh.ConSql;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.io.File;
import java.io.FileWriter;

public class FavoriteMovieDriver {

    public static void main(String[] args) throws Exception {
        // 第一步：从数据库导出数据到文件
        exportFavoriteDataToFile();
        if (args.length != 2) {
            System.err.println("Usage: MovieCommentAnalysis <input path> <output path>");
            System.exit(-1);
        }


        // 配置MapReduce作业
        Configuration conf = new Configuration();
        Job job = Job.getInstance(conf, "Top 3 Favorite Movies");

        job.setJarByClass(FavoriteMovieDriver.class);
        job.setMapperClass(FavoriteMovieMapper.class);
        job.setReducerClass(FavoriteMovieReducer.class);

        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);

        // 设置输入输出路径
        FileInputFormat.addInputPath(job, new Path(args[0]));
        FileOutputFormat.setOutputPath(job, new Path(args[1]));
        // 启动作业并等待完成
        System.exit(job.waitForCompletion(true) ? 0 : 1);
    }

    // 从数据库导出收藏数据到文本文件
    private static void exportFavoriteDataToFile() throws Exception {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        FileWriter writer = null;

        try {
            // 获取数据库连接
            conn = ConSql.getConnection();
            // 查询电影类收藏记录
            String query = "SELECT USERID, CONTENT_ID, CONTENT_TYPE FROM Favorite WHERE CONTENT_TYPE = 'movie'";
            stmt = conn.prepareStatement(query);
            rs = stmt.executeQuery();

            // 创建输入目录(如果不存在)
            new File("input").mkdirs();
            writer = new FileWriter("input/favorite_data.txt");

            // 将每条记录写入文件
            while (rs.next()) {
                String line = String.format("%s,%d,%s%n",
                        rs.getString("USERID"),
                        rs.getInt("CONTENT_ID"),
                        rs.getString("CONTENT_TYPE"));
                writer.write(line);
            }
        } finally {
            // 关闭所有资源
            if (writer != null) writer.close();
            if (rs != null) rs.close();
            if (stmt != null) stmt.close();
            if (conn != null) conn.close();
        }
    }
}
